<?php
/**
 * 同城微聚汇
 * ============================================================================
 * * 版权所有 2015-2027 武汉鼎联信息技术有限公司，并保留所有权利。
 * 网站地址: http://www.同城微聚汇.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: IT宇宙人 2015-08-10 $
 *
 * 为兼容以前的Thinkphp3.2老用户习惯, 用TP5助手函数实现 M( ) D( ) U( ) S( )等单字母函数
 */
use think\Db;

/**
 * 同城微聚汇检验登陆
 * @param
 * @return bool
 */
function is_login(){
    if(isset($_SESSION['admin_id']) && $_SESSION['admin_id'] > 0){
        return $_SESSION['admin_id'];
    }else{
        return false;
    }
}
/**
 * 获取用户信息
 * @param $user_id_or_name  用户id 邮箱 手机 第三方id
 * @param int $type  类型 0 user_id查找 1 邮箱查找 2 手机查找 3 第三方唯一标识查找
 * @param string $oauth  第三方来源
 * @return mixed
 */
function get_user_info($user_id_or_name,$type = 0,$oauth=''){
    $map = array();
    if($type == 0)
        $map['user_id'] = $user_id_or_name;
    if($type == 1)
        $map['email'] = $user_id_or_name;
    if($type == 2)
        $map['mobile'] = $user_id_or_name;
    if($type == 3){
        $map['openid'] = $user_id_or_name;
        $map['oauth'] = $oauth;
    }
    if($type == 4){
    	$map['unionid'] = $user_id_or_name;
    	$map['oauth'] = $oauth;
    }
    $user = M('users')->where($map)->find();

    return $user;
}

/**
 * 更新会员等级,折扣，消费总额
 * @param $user_id  用户ID
 * @return boolean
 */

function update_user_level($user_id){
    $upgrade_stand=tpCache('basic.upgrade_stand');//会员升级标准
    $level_info = M('user_level')->order('level_id')->select();
    //$order = M('order')->where("user_id=:user_id AND pay_status=1 and order_status in (2,4)")->bind(['user_id'=>$user_id])->order('order_id desc')->find();
    $userinfo = M('users')->field('point_amount,total_amount')->where('user_id',$user_id)->find();

    if($upgrade_stand==1){//按累计积分升级 
        $total_amount =  $userinfo['point_amount'];
    }
    if($upgrade_stand==2){//按累计金额升级
        $total_amount =  $userinfo['total_amount'];
    }

    if($level_info){
    	foreach($level_info as $k=>$v){
    		if($total_amount >= $v['amount']){
    			$level = $level_info[$k]['level_id'];
    			$discount = $level_info[$k]['discount']/100;
    		}
    	}
        if($level==1){
            $res1=M('order')->field('goods_price')->where('user_id',$user_id)->order('order_id desc')->find();
            $res2=M('cust_buy_log')->field('sell_val')->where(['user_id'=>$user_id])->order('id desc')->find();
            if($res1['goods_price']>=600||$res2['sell_val']>=600){
                $level=2;
            }
        }
    	$user = session('user');
    	
    	//累计额度达到新等级，更新会员折扣
    	if(isset($level)){
    		$updata['level'] = $level;
    		$updata['discount'] = $discount;	
    	}
        if($updata)
    	M('users')->where("user_id", $user_id)->save($updata);
    }
}

/**
 *  商品缩略图 给于标签调用 拿出商品表的 original_img 原始图来裁切出来的
 * @param type $goods_id  商品id
 * @param type $width     生成缩略图的宽度
 * @param type $height    生成缩略图的高度
 */
function goods_thum_images($goods_id,$width,$height){

     if(empty($goods_id))
		 return '';
    //判断缩略图是否存在
    $path = "public/upload/goods/thumb/$goods_id/";
    $goods_thumb_name ="goods_thumb_{$goods_id}_{$width}_{$height}";
  
    // 这个商品 已经生成过这个比例的图片就直接返回了
    if(file_exists($path.$goods_thumb_name.'.jpg'))  return '/'.$path.$goods_thumb_name.'.jpg'; 
    if(file_exists($path.$goods_thumb_name.'.jpeg')) return '/'.$path.$goods_thumb_name.'.jpeg'; 
    if(file_exists($path.$goods_thumb_name.'.gif'))  return '/'.$path.$goods_thumb_name.'.gif'; 
    if(file_exists($path.$goods_thumb_name.'.png'))  return '/'.$path.$goods_thumb_name.'.png'; 
        
    $original_img = M('Goods')->where("goods_id", $goods_id)->getField('original_img');
    if(empty($original_img)) return '';
    
    $original_img = '.'.$original_img; // 相对路径
    if(!file_exists($original_img)) return '';

    //$image = new \think\Image();
    $image = \think\Image::open($original_img);
        
    $goods_thumb_name = $goods_thumb_name. '.'.$image->type();
    //生成缩略图
    if(!is_dir($path)) 
        mkdir($path,0777,true);
    
    //参考文章 http://www.mb5u.com/biancheng/php/php_84533.html  改动参考 http://www.thinkphp.cn/topic/13542.html
    $image->thumb($width, $height,2)->save($path.$goods_thumb_name,NULL,100); //按照原图的比例生成一个最大为$width*$height的缩略图并保存
    
    //图片水印处理
    $water = tpCache('water');
    if($water['is_mark']==1){
    	$imgresource = './'.$path.$goods_thumb_name;
    	if($width>$water['mark_width'] && $height>$water['mark_height']){
    		if($water['mark_type'] == 'img'){
    			$image->open($imgresource)->water(".".$water['mark_img'],$water['sel'],$water['mark_degree'])->save($imgresource);
    		}else{
    		    //检查字体文件是否存在
    			if(file_exists('./zhjt.ttf')){
    				$image->open($imgresource)->text($water['mark_txt'],'./zhjt.ttf',20,'#000000',$water['sel'])->save($imgresource);
    			}
    		}
    	}
    }
    return '/'.$path.$goods_thumb_name;
}

/**
 * 商品相册缩略图
 */
function get_sub_images($sub_img,$goods_id,$width,$height){
	//判断缩略图是否存在
	$path = "public/upload/goods/thumb/$goods_id/";
	$goods_thumb_name ="goods_sub_thumb_{$sub_img['img_id']}_{$width}_{$height}";
	//这个缩略图 已经生成过这个比例的图片就直接返回了
	if(file_exists($path.$goods_thumb_name.'.jpg'))  return '/'.$path.$goods_thumb_name.'.jpg';
	if(file_exists($path.$goods_thumb_name.'.jpeg')) return '/'.$path.$goods_thumb_name.'.jpeg';
	if(file_exists($path.$goods_thumb_name.'.gif'))  return '/'.$path.$goods_thumb_name.'.gif';
	if(file_exists($path.$goods_thumb_name.'.png'))  return '/'.$path.$goods_thumb_name.'.png';
	
	$original_img = '.'.$sub_img['image_url']; //相对路径
	if(!file_exists($original_img)) return '';
	
	//$image = new \think\Image();
	//$image->open($original_img);
        $image = \think\Image::open($original_img);
	
	$goods_thumb_name = $goods_thumb_name. '.'.$image->type();
	// 生成缩略图
	if(!is_dir($path))
		mkdir($path,777,true);
	$image->thumb($width, $height,2)->save($path.$goods_thumb_name,NULL,100); //按照原图的比例生成一个最大为$width*$height的缩略图并保存
	return '/'.$path.$goods_thumb_name;
}

/**
 * 刷新商品库存, 如果商品有设置规格库存, 则商品总库存 等于 所有规格库存相加
 * @param type $goods_id  商品id
 */
function refresh_stock($goods_id){
    $count = M("SpecGoodsPrice")->where("goods_id", $goods_id)->count();
    if($count == 0) return false; // 没有使用规格方式 没必要更改总库存

    $store_count = M("SpecGoodsPrice")->where("goods_id", $goods_id)->sum('store_count');
    M("Goods")->where("goods_id", $goods_id)->save(array('store_count'=>$store_count)); // 更新商品的总库存
}

/**
 * 根据 order_goods 表扣除商品库存
 * @param type $order_id  订单id
 */
function minus_stock($order_id){
    $orderGoodsArr = M('OrderGoods')->where("order_id", $order_id)->select();
    foreach($orderGoodsArr as $key => $val)
    {
        // 有选择规格的商品
        if(!empty($val['spec_key']))
        {   // 先到规格表里面扣除数量 再重新刷新一个 这件商品的总数量
            M('SpecGoodsPrice')->where(['goods_id'=>$val['goods_id'],'key'=>$val['spec_key']])->setDec('store_count',$val['goods_num']);
            refresh_stock($val['goods_id']);
        }else{
            M('Goods')->where("goods_id", $val['goods_id'])->setDec('store_count',$val['goods_num']); // 直接扣除商品总数量
        }
        M('Goods')->where("goods_id", $val['goods_id'])->setInc('sales_sum',$val['goods_num']); // 增加商品销售量
        //更新活动商品购买量
        if($val['prom_type']==1 || $val['prom_type']==2){
        	$prom = get_goods_promotion($val['goods_id']);
        	if($prom['is_end']==0){
        		$tb = $val['prom_type']==1 ? 'flash_sale' : 'group_buy';
        		M($tb)->where("id", $val['prom_id'])->setInc('buy_num',$val['goods_num']);
        		M($tb)->where("id", $val['prom_id'])->setInc('order_num');
        	}
        }
    }
}

/**
 * 邮件发送
 * @param $to    接收人
 * @param string $subject   邮件标题
 * @param string $content   邮件内容(html模板渲染后的内容)
 * @throws Exception
 * @throws phpmailerException
 */
function send_email($to,$subject='',$content=''){    
    vendor('phpmailer.PHPMailerAutoload'); ////require_once vendor/phpmailer/PHPMailerAutoload.php';
    $mail = new PHPMailer;
    $config = tpCache('smtp');
	$mail->CharSet  = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->isSMTP();
    //Enable SMTP debugging
    // 0 = off (for production use)
    // 1 = client messages
    // 2 = client and server messages
    $mail->SMTPDebug = 0;
    //调试输出格式
	//$mail->Debugoutput = 'html';
    //smtp服务器
    $mail->Host = $config['smtp_server'];
    //端口 - likely to be 25, 465 or 587
    $mail->Port = $config['smtp_port'];
	
	if($mail->Port === 465) $mail->SMTPSecure = 'ssl';// 使用安全协议
    //Whether to use SMTP authentication
    $mail->SMTPAuth = true;
    //用户名
    $mail->Username = $config['smtp_user'];
    //密码
    $mail->Password = $config['smtp_pwd'];
    //Set who the message is to be sent from
    $mail->setFrom($config['smtp_user']);
    //回复地址
    //$mail->addReplyTo('replyto@example.com', 'First Last');
    //接收邮件方
    if(is_array($to)){
    	foreach ($to as $v){
    		$mail->addAddress($v);
    	}
    }else{
    	$mail->addAddress($to);
    }

    $mail->isHTML(true);// send as HTML
    //标题
    $mail->Subject = $subject;
    //HTML内容转换
    $mail->msgHTML($content);
    //Replace the plain text body with one created manually
    //$mail->AltBody = 'This is a plain-text message body';
    //添加附件
    //$mail->addAttachment('images/phpmailer_mini.png');
    //send the message, check for errors
    return $mail->send();
} 

/**
 * 检测是否能够发送短信
 * @param unknown $scene
 * @return multitype:number string
 */
function checkEnableSendSms($scene)
{

    $scenes = C('SEND_SCENE');
    $sceneItem = $scenes[$scene];
    if (!$sceneItem) {
        return array("status" => -1, "msg" => "场景参数'scene'错误!");
    }
    $key = $sceneItem[2];
    $sceneName = $sceneItem[0];
    $config = tpCache('sms');
    $smsEnable = $config[$key];

    if (!$smsEnable) {
        return array("status" => 0, "msg" => "['$sceneName']发送短信被关闭'");
    }
    //判断是否添加"注册模板"
    $size = M('sms_template')->where("send_scene", $scene)->count('tpl_id');
    if (!$size) {
        return array("status" => -1, "msg" => "请先添加['$sceneName']短信模板");
    }
    
    return array("status"=>1,"msg"=>"可以发送短信");
}

/**
 * 发送短信逻辑
 * @param unknown $scene
 */
function sendSms($scene, $sender, $params)
{

    $smsTemp = M('sms_template')->where("send_scene", $scene)->find();    //用户注册.
    $code = !empty($params['code']) ? $params['code'] : false;
    $consignee = !empty($params['consignee']) ? $params['consignee'] : false;
    $user_name =  !empty($params['user_name']) ? $params['user_name'] : false;
    $mobile = !empty($params['mobile']) ? $params['mobile'] : false;
    $order_sn = $params['order_sn'];
    $session_id = session_id();
    $config = tpCache('sms');
    $product = $config['sms_product'];

    $smsParams = array(
        1 => "{\"code\":\"$code\"}",                                                                                                          //1. 用户注册
        2 => "{\"code\":\"$code\"}",                                                                                                          //2. 用户找回密码
        3 => "{\"consignee\":\"$consignee\",\"phone\":\"$mobile\"}",                                                       //3. 客户下单
        4 => "{\"order_sn\":\"$order_sn\"}",                                                                                               //4. 客户支付
        5 => "{\"user_name\":\"$user_name\",\"order_sn\":\"$order_sn\",\"consignee\":\"$consignee\"}",  //5.商家发货
        6 => "{\"user_name\":\"$user_name\",\"code\":\"$code\"}"                                                            //6. 修改手机号码
    );
    
    $smsParam = $smsParams[$scene];
    //提取发送短信内容
    $scenes = C('SEND_SCENE');
    $msg = $scenes[$scene][1];
    $params_arr = json_decode($smsParam);
    foreach ($params_arr as $k => $v) {
        $msg = str_replace('${' . $k . '}', $v, $msg);
    }
    
    //发送记录存储数据库
    $log_id = M('sms_log')->insertGetId(array('mobile' => $sender, 'code' => $code, 'add_time' => time(), 'session_id' => $session_id, 'status' => 0, 'scene' => $scene, 'msg' => $msg));
    $resp = realSendSMS($sender, $smsTemp['sms_sign'], $smsParam, $smsTemp['sms_tpl_code']);
    if ($resp['status'] == 1) {
        M('sms_log')->where(array('id' => $log_id))->save(array('status' => 1)); //修改发送状态为成功
    }else{
        M('sms_log')->where(array('id' => $log_id))->update(array('error_msg'=>$resp['msg'])); //发送失败, 将发送失败信息保存数据库
    }
    return $resp;
}


//    /**
//     * 发送短信
//     * @param $mobile  手机号码
//     * @param $code    验证码
//     * @return bool    短信发送成功返回true失败返回false
//     */
function realSendSMS($mobile, $smsSign, $smsParam , $templateCode)
{
   
    //时区设置：亚洲/上海
    date_default_timezone_set('Asia/Shanghai');
    //这个是你下面实例化的类
    vendor('Alidayu.TopClient');
    //这个是topClient 里面需要实例化一个类所以我们也要加载 不然会报错
    vendor('Alidayu.ResultSet');
    //这个是成功后返回的信息文件
    vendor('Alidayu.RequestCheckUtil');
    //这个是错误信息返回的一个php文件
    vendor('Alidayu.TopLogger');
    //这个也是你下面示例的类
    vendor('Alidayu.AlibabaAliqinFcSmsNumSendRequest');

    $c = new \TopClient;
    $config = tpCache('sms');  
    //App Key的值 这个在开发者控制台的应用管理点击你添加过的应用就有了
    $c->appkey = $config['sms_appkey'];
    //App Secret的值也是在哪里一起的 你点击查看就有了
    $c->secretKey = $config['sms_secretKey'];
    //这个是用户名记录那个用户操作
    $req = new \AlibabaAliqinFcSmsNumSendRequest;
    //代理人编号 可选
    $req->setExtend("123456");
    //短信类型 此处默认 不用修改
    $req->setSmsType("normal");
    //短信签名 必须
    $req->setSmsFreeSignName($smsSign);
    //短信模板 必须
    $req->setSmsParam($smsParam);
    //短信接收号码 支持单个或多个手机号码，传入号码为11位手机号码，不能加0或+86。群发短信需传入多个号码，以英文逗号分隔，
    $req->setRecNum("$mobile");
    //短信模板ID，传入的模板必须是在阿里大鱼“管理中心-短信模板管理”中的可用模板。
    $req->setSmsTemplateCode($templateCode); // templateCode

    $c->format = 'json';
  
    //发送短信
    $resp = $c->execute($req);
    //短信发送成功返回True，失败返回false
    if ($resp && $resp->result) {
        return array('status' => 1, 'msg' => $resp->sub_msg);
    } else {
        return array('status' => -1, 'msg' => $resp->msg . ' ,sub_msg :' . $resp->sub_msg . ' subcode:' . $resp->sub_code);
    }
}

/**
 * 查询快递
 * @param $postcom  快递公司编码
 * @param $getNu  快递单号
 * @return array  物流跟踪信息数组
 */
function queryExpress($postcom , $getNu) {
/*    $url = "http://wap.kuaidi100.com/wap_result.jsp?rand=".time()."&id={$postcom}&fromWeb=null&postid={$getNu}";
    //$resp = httpRequest($url,'GET');
    $resp = file_get_contents($url);
    if (empty($resp)) {
        return array('status'=>0, 'message'=>'物流公司网络异常，请稍后查询');
    }
    preg_match_all('/\\<p\\>&middot;(.*)\\<\\/p\\>/U', $resp, $arr);
    if (!isset($arr[1])) {
        return array( 'status'=>0, 'message'=>'查询失败，参数有误' );
    }else{
        foreach ($arr[1] as $key => $value) {
            $a = array();
            $a = explode('<br /> ', $value);
            $data[$key]['time'] = $a[0];
            $data[$key]['context'] = $a[1];
        }
        return array( 'status'=>1, 'message'=>'1','data'=> array_reverse($data));
    }*/
    $url = "https://m.kuaidi100.com/query?type=".$postcom."&postid=".$getNu."&id=1&valicode=&temp=0.49738534969422676";
    $resp = httpRequest($url,"GET");
    return json_decode($resp,true);
}

/**
 * 获取某个商品分类的 儿子 孙子  重子重孙 的 id
 * @param type $cat_id
 */
function getCatGrandson ($cat_id)
{
    $GLOBALS['catGrandson'] = array();
    $GLOBALS['category_id_arr'] = array();
    // 先把自己的id 保存起来
    $GLOBALS['catGrandson'][] = $cat_id;
    // 把整张表找出来
    $GLOBALS['category_id_arr'] = M('GoodsCategory')->cache(true,TPSHOP_CACHE_TIME)->getField('id,parent_id');
    // 先把所有儿子找出来
    $son_id_arr = M('GoodsCategory')->where("parent_id", $cat_id)->cache(true,TPSHOP_CACHE_TIME)->getField('id',true);
    foreach($son_id_arr as $k => $v)
    {
        getCatGrandson2($v);
    }
    return $GLOBALS['catGrandson'];
}
/**
 * 获取某个商品分类的 儿子 孙子  重子重孙 的 id
 * @param type $cat_id
 */
function getCatGrandson_two ($cat_id)
{
    $GLOBALS['catGrandson2'] = array();
    $GLOBALS['category_id_arr2'] = array();
    // 先把自己的id 保存起来
    $GLOBALS['catGrandson2'][] = $cat_id;
    // 把整张表找出来
    $GLOBALS['category_id_arr2'] = M('GoodsCategoryAdmin')->cache(true,TPSHOP_CACHE_TIME)->getField('id,parent_id');
    // 先把所有儿子找出来
    $son_id_arr = M('GoodsCategoryAdmin')->where("parent_id", $cat_id)->cache(true,TPSHOP_CACHE_TIME)->getField('id',true);
    foreach($son_id_arr as $k => $v)
    {
        getCatGrandson2_two($v);
    }
    return $GLOBALS['catGrandson2'];
}
/**
 * 获取某个文章分类的 儿子 孙子  重子重孙 的 id
 * @param type $cat_id
 */
function getArticleCatGrandson ($cat_id)
{
    $GLOBALS['ArticleCatGrandson'] = array();
    $GLOBALS['cat_id_arr'] = array();
    // 先把自己的id 保存起来
    $GLOBALS['ArticleCatGrandson'][] = $cat_id;
    // 把整张表找出来
    $GLOBALS['cat_id_arr'] = M('ArticleCat')->getField('cat_id,parent_id');
    // 先把所有儿子找出来
    $son_id_arr = M('ArticleCat')->where("parent_id", $cat_id)->getField('cat_id',true);
    foreach($son_id_arr as $k => $v)
    {
        getArticleCatGrandson2($v);
    }
    return $GLOBALS['ArticleCatGrandson'];
}

/**
 * 递归调用找到 重子重孙
 * @param type $cat_id
 */
function getCatGrandson2($cat_id)
{
    $GLOBALS['catGrandson'][] = $cat_id;
    foreach($GLOBALS['category_id_arr'] as $k => $v)
    {
        // 找到孙子
        if($v == $cat_id)
        {
            getCatGrandson2($k); // 继续找孙子
        }
    }
}
function getCatGrandson2_two($cat_id)
{
    $GLOBALS['catGrandson2'][] = $cat_id;
    foreach($GLOBALS['category_id_arr2'] as $k => $v)
    {
        // 找到孙子
        if($v == $cat_id)
        {
            getCatGrandson2_two($k); // 继续找孙子
        }
    }
}

/**
 * 递归调用找到 重子重孙
 * @param type $cat_id
 */
function getArticleCatGrandson2($cat_id)
{
    $GLOBALS['ArticleCatGrandson'][] = $cat_id;
    foreach($GLOBALS['cat_id_arr'] as $k => $v)
    {
        // 找到孙子
        if($v == $cat_id)
        {
            getArticleCatGrandson2($k); // 继续找孙子
        }
    }
}

/**
 * 查看某个用户购物车中商品的数量
 * @param type $user_id
 * @param type $session_id
 * @return type 购买数量
 */
function cart_goods_num($user_id = 0,$session_id = '')
{
//    $where = " session_id = '$session_id' ";
//    $user_id && $where .= " or user_id = $user_id ";
    // 查找购物车数量
//    $cart_count =  M('Cart')->where($where)->sum('goods_num');
    $cart_count = Db::name('cart')->where(function ($query) use ($user_id, $session_id) {
        $query->where('session_id', $session_id);
        if ($user_id) {
            $query->whereOr('user_id', $user_id);
        }
    })->sum('goods_num');
    $cart_count = $cart_count ? $cart_count : 0;
    return $cart_count;
}

/**
 * 获取商品库存
 * @param type $goods_id 商品id
 * @param type $key  库存 key
 */
function getGoodNum($goods_id,$key)
{
    if(!empty($key))
        return M("SpecGoodsPrice")->where(['goods_id' => $goods_id, 'key' => $key])->getField('store_count');
    else
        return  M("Goods")->where("goods_id", $goods_id)->getField('store_count');
}
 
/**
 * 获取缓存或者更新缓存
 * @param string $config_key 缓存文件名称
 * @param array $data 缓存数据  array('k1'=>'v1','k2'=>'v3')
 * @return array or string or bool
 */
function tpCache($config_key,$data = array()){
    $param = explode('.', $config_key);
    if(empty($data)){
        //如$config_key=shop_info则获取网站信息数组
        //如$config_key=shop_info.logo则获取网站logo字符串
        $config = F($param[0],'',TEMP_PATH);//直接获取缓存文件
        if(empty($config)){
            //缓存文件不存在就读取数据库
            $res = D('config')->where("inc_type",$param[0])->select();
            if($res){
                foreach($res as $k=>$val){
                    $config[$val['name']] = $val['value'];
                }
                F($param[0],$config,TEMP_PATH);
            }
        }
        if(count($param)>1){
            return $config[$param[1]];
        }else{
            return $config;
        }
    }else{
        //更新缓存
        $result =  D('config')->where("inc_type", $param[0])->select();
        if($result){
            foreach($result as $val){
                $temp[$val['name']] = $val['value'];
            }
            foreach ($data as $k=>$v){
                $newArr = array('name'=>$k,'value'=>trim($v),'inc_type'=>$param[0]);
                if(!isset($temp[$k])){
                    M('config')->add($newArr);//新key数据插入数据库
                }else{
                    if($v!=$temp[$k])
                        M('config')->where("name", $k)->save($newArr);//缓存key存在且值有变更新此项
                }
            }
            //更新后的数据库记录
            $newRes = D('config')->where("inc_type", $param[0])->select();
            foreach ($newRes as $rs){
                $newData[$rs['name']] = $rs['value'];
            }
        }else{
            foreach($data as $k=>$v){
                $newArr[] = array('name'=>$k,'value'=>trim($v),'inc_type'=>$param[0]);
            }
            M('config')->insertAll($newArr);
            $newData = $data;
        }
        return F($param[0],$newData,TEMP_PATH);
    }
}



/**
 * 记录帐户变动
 * @param   int     $user_id        用户id
 * @param   float   $user_money     可用余额变动
 * @param   int     $pay_points     消费积分变动
 * @param   string  $desc    变动说明
 * @param   float   distribut_money 分佣金额
 * @return  bool
 */
function accountLog($user_id, $user_money = 0,$pay_points = 0, $desc = '',$distribut_money = 0,$type='',$level=''){
    /* 插入帐户变动记录 */
    $account_log = array(
        'user_id'       => $user_id,
        'user_money'    => $user_money,
        'pay_points'    => $pay_points,
        'distribut_money'    => $distribut_money,
        'change_time'   => time(),
        'desc'   => $desc,
    );
    $user_money=($user_money<0)?$user_money:'+'.$user_money;
    $pay_points=($pay_points<0)?$pay_points:'+'.$pay_points;
    $distribut_money=($distribut_money<0)?$distribut_money:'+'.$distribut_money;

    /* 更新用户信息 */
    if($type == 'recharge'){
        $update_data = array(
            'user_money'        => ['exp','user_money'.$user_money],
            'pay_points'        => ['exp','pay_points'.$pay_points],
            'distribut_money'   => ['exp','distribut_money'.$distribut_money],
        );
    }elseif($type == 'distribut_recharge'){
        $update_data = array(
            'profit_level'        => $level['level_id'],
            'frozen_money'   => $level['amount'],
        );
    }elseif($type == 'order'){
        $update_data = array(
            'pay_points'        => ['exp','pay_points'.$pay_points],
            'point_amount'   => ['exp','point_amount'.$pay_points],
        );
    }elseif($type=="reg"){
        $update_data = array(
            'pay_points'        => ['exp','pay_points'.$pay_points],
            'point_amount'   => ['exp','point_amount'.$pay_points],
        );
        
    }elseif($type == 'unfreeze'){
        $update_data = array(
            'profit_level'        => $level['level_id'],
            'distribut_money'   => ['exp','distribut_money'.$distribut_money],
            'user_money'        => ['exp','user_money'.$user_money],
        );
    }else{
        $update_data = array(
            'user_money'        => ['exp','user_money'.$user_money],
            'pay_points'        => ['exp','pay_points'.$pay_points],
            'distribut_money'   => ['exp','distribut_money'.$distribut_money],
        );
    }
  
    $update = Db::name('users')->where('user_id',$user_id)->update($update_data);
    if($update){
        M('account_log')->add($account_log);
        // 如果有微信公众号 则推送一条消息到微信
        $user = M('users')->where('user_id',$user_id)->find();
        $level = M('user_level')->where('level_id',$user['level'])->find();
        $level_dist = M('user_level_distribution')->where('level_id',$user['profit_level'])->find();
        
        $level_list = M('user_level')->select();
        if($type == 'reg'){
            update_user_level($user_id);
        }
        switch ($type) {
            case 'recharge':
                 //充值模板
                $wx_content = '充值成功！您的当前余额为：'.$user['user_money'].';可用积分为：'.$user['pay_points'];
                $wx_tplarr=array (
                    'first' => 
                    array (
                      'value' => '尊敬的'.shownickname($user['nickname']).'，您已充值成功',
                      'color' => '#333',
                    ),
                    'keyword1' => 
                    array (
                      'value' => '第七感觉百货',
                      'color' => '#333',
                    ),
                    'keyword2' => 
                    array (
                      'value' => $level['level_name'],
                      'color' => '#333',
                    ),
                    'keyword3' => 
                    array (
                      'value' => $user_money,
                      'color' => '#333',
                    ),
                    'keyword4' => 
                    array (
                      'value' => $user['user_money'],
                      'color' => '#333',
                    ),
                    'keyword5' => 
                    array (
                      'value' => date('Y-m-d H:i:s'),
                      'color' => '#333',
                    ),
                    'remark' => 
                    array (
                      'value' => '感谢您的使用,如有疑问,请微信留言我们！',
                      'color' => '#333',
                    )
                 );
               
                $url="/mobile/User/points/type/recharge.html";
                break;
            case 'distribut_recharge':
                 //充值模板
                $wx_tplarr=array (
                    'first' => 
                    array (
                      'value' => '尊敬的'.shownickname($user['nickname']).'，您分销充值成功，分销等级成为'.$level_dist['level_name'],
                      'color' => '#333',
                    ),
                    'keyword1' => 
                    array (
                      'value' => '第七感觉百货',
                      'color' => '#333',
                    ),
                    'keyword2' => 
                    array (
                      'value' => $level_dist['level_name'],
                      'color' => '#333',
                    ),
                    'keyword3' => 
                    array (
                      'value' => $distribut_money,
                      'color' => '#333',
                    ),
                    'keyword4' => 
                    array (
                      'value' => $user['distribut_money'],
                      'color' => '#333',
                    ),
                    'keyword5' => 
                    array (
                      'value' => date('Y-m-d H:i:s'),
                      'color' => '#333',
                    ),
                    'remark' => 
                    array (
                      'value' => '感谢您的使用,如需退出分销,可在'.$level_dist['allow_time'].'天后申请提现分销押金！',
                      'color' => '#333',
                    )
                 );
                break;
            case 'order':
                 //商品购买成功确认模板
               $wx_content = '恭喜，您已是我们的：' . $level['level_name'] . '，本次购物系统赠送您' . $pay_points . '积分，距离升级' .$level_list[$level['level_id']]['level_name']. '还差' . ($level_list[$level['level_id']]['amount']-$user['pay_points']).'积分。';
               $wx_tplarr=array (
                   'first' => 
                   array (
                     'value' => '亲爱的'.$level['level_name'].'会员'.shownickname($user['nickname']).'，您的积分有新的变动，具体内容如下',
                     'color' => '#333',
                   ),
                   'keyword1' => 
                    array (
                     'value' => date('Y-m-d H:i:s'),
                     'color' => '#333',
                   ),
                   'keyword2' => 
                   array (
                     'value' =>  $pay_points,
                     'color' => '#333',
                   ),
                   'keyword3' => 
                   array (
                     'value' => $desc,
                     'color' => '#333',
                   ),
                   'keyword4' => 
                   array (
                     'value' => $user['pay_points'],
                     'color' => '#333',
                   ),
                   'remark' => 
                   array (
                     'value' => '距离升级' .$level_list[$level['level_id']]['level_name']. '还差' . ($level_list[$level['level_id']]['amount']-$user['pay_points']).'积分。',
                     'color' => '#333',
                   )
                );
                $url="/mobile/User/points/type/points.html";
                break;
            case 'reg':
                 //注册模板
               $wx_content="恭喜您，注册成功！已赠送{$pay_points}积分给您。";
               $wx_tplarr=array (
                   'first' => 
                   array (
                     'value' => '恭喜您，注册成功！',
                     'color' => '#333',
                   ),
                   'keyword1' => 
                   array (
                     'value' => shownickname($user['nickname']),
                     'color' => '#333',
                   ),
                   'keyword2' => 
                   array (
                     'value' => date('Y-m-d H:i:s'),
                     'color' => '#333',
                   ),
                   'remark' => 
                   array (
                     'value' => '谢谢你的注册，获取'.$pay_points.'的消费积分',
                     'color' => '#333',
                   )
                );
                $url='/Mobile/User/userinfo.html';
                break;
                case 'order_action':
                     //订单活动赠送积分
                   $wx_content="恭喜您，系统已经赠送{$pay_points}积分给您。";
                   $wx_tplarr=array (
                       'first' => 
                       array (
                         'value' => '亲爱的'.$level['level_name'].'会员'.shownickname($user['nickname']).'，您的积分有新的变动，具体内容如下',
                         'color' => '#333',
                       ),
                       'keyword1' => 
                        array (
                         'value' => date('Y-m-d H:i:s'),
                         'color' => '#333',
                       ),
                       'keyword2' => 
                       array (
                         'value' =>  $pay_points,
                         'color' => '#333',
                       ),
                       'keyword3' => 
                       array (
                         'value' => $desc,
                         'color' => '#333',
                       ),
                       'keyword4' => 
                       array (
                         'value' => $user['pay_points'],
                         'color' => '#333',
                       ),
                       'remark' => 
                       array (
                         'value' => '距离升级' .$level_list[$level['level_id']]['level_name']. '还差' . ($level_list[$level['level_id']]['amount']-$user['pay_points']).'积分。',
                         'color' => '#333',
                       )
                    );
                    $url='/mobile/User/points/type/points.html';
                    break;
                    case 'give_points':
                     //转增积分
                   $wx_tplarr=array (
                       'first' => 
                       array (
                         'value' => '亲爱的'.$level['level_name'].'会员'.shownickname($user['nickname']).'，您的积分有新的变动，具体内容如下',
                         'color' => '#333',
                       ),
                       'keyword1' => 
                        array (
                         'value' => date('Y-m-d H:i:s'),
                         'color' => '#333',
                       ),
                       'keyword2' => 
                       array (
                         'value' =>  $pay_points,
                         'color' => '#333',
                       ),
                       'keyword3' => 
                       array (
                         'value' => '好友转增',
                         'color' => '#333',
                       ),
                       'keyword4' => 
                       array (
                         'value' => $user['pay_points'],
                         'color' => '#333',
                       ),
                       'remark' => 
                       array (
                         'value' => '距离升级' .$level_list[$level['level_id']]['level_name']. '还差' . ($level_list[$level['level_id']]['amount']-$user['pay_points']).'积分。',
                         'color' => '#333',
                       )
                    );
                    $url='/mobile/User/points/type/points.html';
                    break;
                    case 'recharge_give':
                    $wx_tplarr=array (
                        'first' => 
                        array (
                          'value' => '亲爱的'.$level['level_name'].'会员'.shownickname($user['nickname']).'，您的余额有新的变动，具体内容如下',
                          'color' => '#333',
                        ),
                        'keyword1' => 
                         array (
                          'value' => date('Y-m-d H:i:s'),
                          'color' => '#333',
                        ),
                        'keyword2' => 
                        array (
                          'value' =>  '充值赠送',
                          'color' => '#FF4040',
                        ),
                        'keyword3' => 
                        array (
                          'value' => $user_money,
                          'color' => '#FF4040',
                        ),
                        'keyword4' => 
                        array (
                          'value' =>$user['user_money'] ,
                          'color' => '#333',
                        ),
                        'remark' => 
                        array (
                          'value' => '详情请点击此消息进入会员中心-余额记录进行查询!',
                          'color' => '#333',
                        )
                     );
                     $url='/mobile/User/points/type/recharge.html';
                     break;
                default:
                # code...
                break;
        }
         
        //push_wxmessage($user_id,$wx_content);
        push_wxtplmessage($user_id,$wx_tplarr,$url,$type);
        return true;
    }else{
        return false;
    }
}

/**
 * 订单操作日志
 * 参数示例
 * @param type $order_id  订单id
 * @param type $action_note 操作备注
 * @param type $status_desc 操作状态  提交订单, 付款成功, 取消, 等待收货, 完成
 * @param type $user_id  用户id 默认为管理员
 * @return boolean
 */
function logOrder($order_id,$action_note,$status_desc,$user_id = 0)
{
    $status_desc_arr = array('提交订单', '付款成功', '取消', '等待收货', '完成','退货');
    // if(!in_array($status_desc, $status_desc_arr))
    // return false;

    $order = M('order')->where("order_id", $order_id)->find();
    $action_info = array(
        'order_id'        =>$order_id,
        'action_user'     =>$user_id,
        'order_status'    =>$order['order_status'],
        'shipping_status' =>$order['shipping_status'],
        'pay_status'      =>$order['pay_status'],
        'action_note'     => $action_note,
        'status_desc'     =>$status_desc, //''
        'log_time'        =>time(),
    );
    return M('order_action')->add($action_info);
}

/*
 * 获取地区列表
 */
function get_region_list(){
    //获取地址列表 缓存读取
    if(!S('region_list')){
        $region_list = M('region')->select();
        $region_list = convert_arr_key($region_list,'id');        
        S('region_list',$region_list);
    }

    return $region_list ? $region_list : S('region_list');
}
/*
 * 获取用户地址列表
 */
function get_user_address_list($user_id){
    $lists = M('user_address')->where(array('user_id'=>$user_id))->select();
    return $lists;
}

/*
 * 获取指定地址信息
 */
function get_user_address_info($user_id,$address_id){
    $data = M('user_address')->where(array('user_id'=>$user_id,'address_id'=>$address_id))->find();
    return $data;
}
/*
 * 获取用户默认收货地址
 */
function get_user_default_address($user_id){
    $data = M('user_address')->where(array('user_id'=>$user_id,'is_default'=>1))->find();
    return $data;
}
/**
 * 获取订单状态的 中文描述名称
 * @param type $order_id  订单id
 * @param type $order     订单数组
 * @return string
 */
function orderStatusDesc($order_id = 0, $order = array())
{
    if(empty($order))
        $order = M('Order')->where("order_id", $order_id)->find();

    // 货到付款
    if($order['pay_code'] == 'cod')
    {
        if(in_array($order['order_status'],array(0,1)) && $order['shipping_status'] == 0)
            return 'WAITSEND'; //'待发货',
    }
    else // 非货到付款
    {
        if($order['pay_status'] == 0 && $order['order_status'] == 0)
            return 'WAITPAY'; //'待支付',
        if($order['pay_status'] == 1 &&  in_array($order['order_status'],array(0,1)) && $order['shipping_status'] != 1)
            return 'WAITSEND'; //'待发货',
    }
    if(($order['shipping_status'] == 1) && ($order['order_status'] == 1))
        return 'WAITRECEIVE'; //'待收货',
    if($order['order_status'] == 2)
        return 'WAITCCOMMENT'; //'待评价',
    if($order['order_status'] == 3)
        return 'CANCEL'; //'已取消',
    if($order['order_status'] == 4)
        return 'FINISH'; //'已完成',
    if($order['order_status'] == 5)
    	return 'CANCELLED'; //'已作废',
    return 'OTHER';
}

/**
 * 获取订单状态的 显示按钮
 * @param type $order_id  订单id
 * @param type $order     订单数组
 * @return array()
 */
function orderBtn($order_id = 0, $order = array())
{
    if(empty($order))
        $order = M('Order')->where("order_id", $order_id)->find();
    /**
     *  订单用户端显示按钮
    去支付     AND pay_status=0 AND order_status=0 AND pay_code ! ="cod"
    取消按钮  AND pay_status=0 AND shipping_status=0 AND order_status=0
    确认收货  AND shipping_status=1 AND order_status=0
    评价      AND order_status=1
    查看物流  if(!empty(物流单号))
     */
    $btn_arr = array(
        'pay_btn' => 0, // 去支付按钮
        'cancel_btn' => 0, // 取消按钮
        'receive_btn' => 0, // 确认收货
        'comment_btn' => 0, // 评价按钮
        'shipping_btn' => 0, // 查看物流
        'return_btn' => 0, // 退货按钮 (联系客服)
    );


    // 货到付款
    if($order['pay_code'] == 'cod')
    {
        if(($order['order_status']==0 || $order['order_status']==1) && $order['shipping_status'] == 0) // 待发货
        {
            $btn_arr['cancel_btn'] = 1; // 取消按钮 (联系客服)
        }
        if($order['shipping_status'] == 1 && $order['order_status'] == 1) //待收货
        {
            $btn_arr['receive_btn'] = 1;  // 确认收货
            $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
        }       
    }
    // 非货到付款
    else
    {
        if($order['pay_status'] == 0 && $order['order_status'] == 0) // 待支付,待确认
        {
            $btn_arr['pay_btn'] = 1; // 去支付按钮
            $btn_arr['cancel_btn'] = 1; // 取消按钮
        }
        if($order['pay_status'] == 1 && $order['shipping_status'] == 0&&$order['order_status'] <2) // 已支付,未发货,未取消
        {
            $btn_arr['cancel_btn'] = 1; // 取消按钮
        }
        if($order['pay_status'] == 1 && in_array($order['order_status'],array(0,1)) && $order['shipping_status'] == 0) // 待发货
        {
            $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
        }
        if($order['pay_status'] == 1 && $order['order_status'] == 1  && $order['shipping_status'] == 1) //待收货
        {
            $btn_arr['receive_btn'] = 1;  // 确认收货
            $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
        }
    }
    if($order['order_status'] == 2)
    {
        $btn_arr['comment_btn'] = 1;  // 评价按钮
        $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
    }
    if($order['shipping_status'] != 0)
    {
        $btn_arr['shipping_btn'] = 1; // 查看物流
    }
    if($order['shipping_status'] == 2 && $order['order_status'] == 1) // 部分发货
    {            
        $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
    }
    
    return $btn_arr;
}

/**
 * 给订单数组添加属性  包括按钮显示属性 和 订单状态显示属性
 * @param type $order
 */
function set_btn_order_status($order)
{
    $order_status_arr = C('ORDER_STATUS_DESC');
    $order['order_status_code'] = $order_status_code = orderStatusDesc(0, $order); // 订单状态显示给用户看的
    $order['order_status_desc'] = $order_status_arr[$order_status_code];
    $orderBtnArr = orderBtn(0, $order);
    return array_merge($order,$orderBtnArr); // 订单该显示的按钮
}

/**
 * 支付完成修改订单
 * @param $order_sn 订单号
 * @param array $ext 额外参数
 * @return bool|void
 */
function update_pay_status($order_sn,$ext=array())
{
	if(stripos($order_sn,'recharge') !== false){
		//用户在线充值
		$count = M('recharge')->where(['order_sn'=>$order_sn,'pay_status'=>0])->count();   // 看看有没已经处理过这笔订单  支付宝返回不重复处理操作
		if($count == 0) return false;
		$order = M('recharge')->where("order_sn", $order_sn)->find();
		$ress=M('recharge')->where("order_sn",$order_sn)->save(array('pay_status'=>1,'pay_time'=>time()));
		$result=accountLog($order['user_id'],$order['account'],0,'会员在线充值',0,'recharge');
        return $result;
	}elseif(stripos($order_sn,'distribut') !== false) {
        //用户在线充值
        $count = M('recharge')->where(['order_sn'=>$order_sn,'pay_status'=>0])->count();   // 看看有没已经处理过这笔订单  支付宝返回不重复处理操作
        if($count == 0) return false;
        $order = M('recharge')->where("order_sn", $order_sn)->find();
//        M('recharge')->where("order_sn",$order_sn)->save(array('pay_status'=>1,'pay_time'=>time()));
        $user = M('users')->field('frozen_money')->where('user_id',$order['user_id'])->find();
        $account = $user['frozen_money'] + $order['account'];
        $distribut = M('user_level_distribution')->where('amount = '.$account)->find();
        $result=accountLog($order['user_id'],0,0,'分销充值',$order['account'],'distribut_recharge',$distribut);
        return $result;
    }else{
		// 如果这笔订单已经处理过了
		$count = M('order')->where("order_sn = :order_sn and pay_status = 0 OR pay_status = 2")->bind(['order_sn'=>$order_sn])->count();   // 看看有没已经处理过这笔订单  支付宝返回不重复处理操作
		if($count == 0) return false;
		// 找出对应的订单
        $order = M('order')->where("order_sn",$order_sn)->find();
        //预售订单
        if ($order['order_prom_type'] == 4) {
            // 预付款支付 有订金支付 修改支付状态  部分支付
            if($order['total_amount'] != $order['order_amount'] && $order['pay_status'] == 0){
                //支付订金
                M('order')->where("order_sn", $order_sn)->save(array('order_sn'=> date('YmdHis').mt_rand(1000,9999) ,'pay_status' => 2, 'pay_time' => time(),'paid_money'=>$order['order_amount']));
            }else{
                //全额支付 无订金支付 支付尾款
                M('order')->where("order_sn", $order_sn)->save(array('pay_status' => 1, 'pay_time' => time()));
            }
            $orderGoodsArr = M('OrderGoods')->where(array('order_id'=>$order['order_id']))->find();
            M('goods_activity')->where(array('act_id'=>$order['order_prom_id']))->setInc('act_count',$orderGoodsArr['goods_num']);

        } else {
            // 修改支付状态  已支付
            if($order['order_amount']==0){
                $statuss['pay_code']="balance";
                $statuss['pay_name']="余额支付";
            }
            $statuss['pay_status']=1;
            $statuss['pay_time']=time();
            M('order')->where("order_sn", $order_sn)->save($statuss);

            M('order')->where("order_sn", $order_sn)->save(array('pay_status'=>1,'pay_time'=>time()));
            //统计累计消费金额
            $total_amount=M('order_goods')->where("order_id", $order['order_id'])->sum('goods_num*member_goods_price');
            M('users')->where('user_id', $order['user_id'])->save(array("total_amount" => ["exp", "total_amount+" . $total_amount]));
            
        }
		// 减少对应商品的库存
		minus_stock($order['order_id']);
		// 给他升级, 根据order表查看消费记录 给他会员等级升级 修改他的折扣 和 总金额
//		update_user_level($order['user_id']);
		// 记录订单操作日志
        if(array_key_exists('admin_id',$ext)){
            logOrder($order['order_id'],$ext['note'],'付款成功',$ext['admin_id']);
        }else{
            logOrder($order['order_id'],'订单付款成功','付款成功',$order['user_id']);
        }
		//分销设置
		M('rebate_log')->where("order_id" ,$order['order_id'])->save(array('status'=>1));
		// 成为分销商条件
		$distribut_condition = tpCache('distribut.condition');
		if($distribut_condition == 1)  // 购买商品付款才可以成为分销商
			M('users')->where("user_id", $order['user_id'])->save(array('is_distribut'=>1));
		
		//用户支付, 发送短信给商家
		$res = checkEnableSendSms("4");
		if(!$res || $res['status'] !=1) return ;
			
		$sender = tpCache("shop_info.mobile");
		if(empty($sender))return;
		$params = array('order_sn'=>$order_sn);
		sendSms("4", $sender, $params);
        return true;
	}

}

    /**
     * 订单确认收货
     * @param $id   订单id
     */
    function confirm_order($id,$user_id = 0){
        $where['order_id'] = $id;
        if($user_id){
            $where['user_id'] = $user_id;
        }
        $order = M('order')->where($where)->find();
//        order_give($order);die;
        if($order['order_status'] == 2)
            return array('status'=>-1,'msg'=>'该订单已确认收货');
        if($order['order_status'] != 1)
            return array('status'=>-1,'msg'=>'该订单已操作过');
        $data['order_status'] = 2; // 已收货        
        $data['pay_status'] = 1; // 已付款        
        $data['confirm_time'] = time(); // 收货确认时间
        if($order['pay_code'] == 'cod'){
        	$data['pay_time'] = time();
        }
        $row = M('order')->where(array('order_id'=>$id))->save($data);
        if(!$row)
            return array('status'=>-3,'msg'=>'操作失败');
        order_give($order);// 给订单送券送积分 送东西
        update_user_level($order['user_id']);//更新会员等级
        //分销设置
        M('rebate_log')->where("order_id", $id)->save(array('status'=>2,'confirm'=>time()));
               
        return array('status'=>1,'msg'=>'操作成功');
    }

/**
 * 给订单送券送积分 送东西
 */
function order_give($order)
{
	$order_goods = M('order_goods')->where("order_id",$order['order_id'])->cache(true)->select();

	//查找购买商品送优惠券活动
	foreach ($order_goods as $key=>$val)
    {
		if($val['prom_type'] == 3)
        {
			$prom = M('prom_goods')->where('type=3 and id=:id')->bind(['id'=>$val['prom_id']])->find();
			if($prom){
				$coupon = M('coupon')->where("id", $prom['expression'])->find();//查找优惠券模板
				if($coupon && $coupon['createnum']>0){
                    $remain = $coupon['createnum'] - $coupon['send_num'];//剩余派发量
                    if($remain > 0)
                    {
                        $data = array('cid'=>$coupon['id'],'type'=>$coupon['type'],'uid'=>$order['user_id'],'send_time'=>time());
                        M('coupon_list')->add($data);
                        M('Coupon')->where("id", $coupon['id'])->setInc('send_num'); // 优惠券领取数量加一
                        $coupon = M('coupon')->where("id",$coupon['id'])->find();//查找优惠券模板
                        $tplarr=array(
                            'title'=>'您有一张'.$coupon['name'].'注意查收',
                            'description'=>'有效期：'.date('Y-m-d',$coupon['use_start_time']).'~'.date('Y-m-d',$coupon['use_end_time']),
                            'url'=>$coupon['coupon_url'],
                            'picurl'=>$coupon['coupon_picurl'],
                            );
                        push_wxmessage($order['user_id'], $tplarr,'news');
                    }
				}
		 	}
		 }
	}

    $goods = M('order_goods')->field('sum(member_goods_price*goods_num) as money,suppliers_id')->where("order_id",$order['order_id'])->group('suppliers_id')->select();

    //查找订单满额送优惠券活动
    foreach ($goods as $k => $v) {
        $pay_time = $order['pay_time'];
        $prom_order_where = [
            'type' => ['gt', 1],
            'end_time' => ['gt', $pay_time],
            'start_time' => ['lt', $pay_time],
            'money' => ['elt', $v['money']],
            'suppliers_id' =>$v['suppliers_id'],
        ];
        $prom[] = M('prom_order')
            ->where($prom_order_where)
            ->order('money desc')
            ->find();
    }

    foreach ($prom as $k=>$v){
        if ($prom) {
            if ($v['type'] == 3) {
                $coupon = M('coupon')->where("id", $v['expression'])->find();//查找优惠券模板
                if ($coupon) {
                    if ($coupon['createnum'] > 0) {
                        $remain = $coupon['createnum'] - $coupon['send_num'];//剩余派发量
                        if ($remain > 0) {
                            $data = array('cid' => $coupon['id'], 'type' => $coupon['type'], 'uid' => $order['user_id'], 'send_time' => time());
                            M('coupon_list')->add($data);
                            M('Coupon')->where("id", $coupon['id'])->setInc('send_num'); // 优惠券领取数量加一
                            //$wx_content = '恭喜您：获得'.$coupon['name'];
                            $tplarr = array(
                                'title' => '您有一张' . $coupon['name'] . '注意查收',
                                'description' => '有效期：' . date('Y-m-d', $coupon['use_start_time']) . '~' . date('Y-m-d', $coupon['use_end_time']),
                                'url' => $coupon['coupon_url'],
                                'picurl' => $coupon['coupon_picurl'],
                            );
                            push_wxmessage($order['user_id'], $tplarr, 'news');
                        }
                    }
                }
            } else if ($v['type'] == 2) {

                M('users')->where('user_id', $order['user_id'])->save(array("point_amount" => array("exp", "point_amount+" . $v['expression'])));
                update_user_level($order['user_id']);
                accountLog($order['user_id'], 0, $v['expression'], "订单活动赠送积分", 0, "order_action");

            }
        }
    }

    $points = M('order_goods')->where("order_id", $order['order_id'])->sum("give_integral * goods_num");
    $points && accountLog($order['user_id'], 0,$points,"下单赠送积分",0,'order');
}


/**
 * 查看商品是否有活动
 * @param goods_id 商品ID
 */

function get_goods_promotion($goods_id,$user_id=0){
	$now = time();
	$goods = M('goods')->where("goods_id", $goods_id)->find();
    if(empty($goods)){
        return false;
    }
    $where['id'] = $goods['prom_id'];
    $goods['price']=$goods['shop_price'];//该商品的现卖价格
    $goods['is_end'] = 0;//正在销售中
	//抢购
	if($goods['prom_type'] == 1){
		$prominfo = M('flash_sale')->where($where)->find();
		if(!empty($prominfo)){
            $goods['price'] = $prominfo['price'];
            $goods['buy_num']=$prominfo['buy_num'];
            $goods['goods_num']=$prominfo['goods_num'];
			if($prominfo['goods_num'] == $prominfo['buy_num']){
				$goods['is_end'] = 2;//已售馨
			}elseif($prominfo['start_time']>time()){
                $goods['is_end'] = 4;//活动尚未开始
            }elseif($prominfo['end_time']<time()){
                $goods['is_end'] = 5;//活动已结束
            }else{
				//核查用户购买数量
				$where = "user_id = :user_id and order_status!=3 and  add_time>".$prominfo['start_time']." and add_time<".$prominfo['end_time'];
				$order_id_arr = M('order')->where($where)->bind(['user_id'=>$user_id])->getField('order_id',true);
				if($order_id_arr){
					$goods_num = M('order_goods')->where("prom_id={$goods['prom_id']} and prom_type={$goods['prom_type']} and order_id in (".implode(',', $order_id_arr).")")->sum('goods_num');
					if($goods_num < $prominfo['buy_limit']){
						$goods['price'] = $prominfo['price'];
					}else{
                        $goods['is_end'] = 3;//已达到限购值
                    }
				}
              /*  //统计该商品总共售出数量
                $condition="t0.goods_id={$goods_id} and t0.prom_type={$goods['prom_type']} and prom_id={$goods['prom_id']} and  t1.add_time>".$prominfo['start_time']." and t1.add_time<".$prominfo['end_time'];
                $prom['total_sale_num'] = M('order_goods t0')->field('t0.*,t1.add_time')->join('tp_order t1','t0.order_id=t1.order_id','left')->where($condition)->sum('goods_num');*/
			} 				
		}
	}
	//团购
	if($goods['prom_type']==2){
		$prominfo = M('group_buy')->where($where)->find();
		if(!empty($prominfo)){
            $goods['goods_num']=$prominfo['goods_num'];
            $goods['buy_num']=$prominfo['buy_num'];
            $goods['virtual_num']=$prominfo['virtual_num'];
			if($prominfo['goods_num'] == $prominfo['buy_num']){
				$goods['is_end'] = 2;//已售馨
			}elseif($prominfo['start_time']>time()){
                $goods['is_end'] = 4;//活动尚未开始
            }elseif($prominfo['end_time']<time()){
                $goods['is_end'] = 5;//活动已结束
            }else{
				$goods['price'] = $prominfo['price'];
			}				
		}
	}
    //优惠促销
	if($goods['prom_type'] == 3){
		$parse_type = array('0'=>'直接打折','1'=>'减价优惠','2'=>'固定金额出售','3'=>'买就赠优惠券','4'=>'买M件送N件');
        $where['start_time']=array('lt',time());
        $where['end_time']=array('gt',time());
		$prominfo = M('prom_goods')->where($where)->find();
		if(!empty($prominfo)){
			if($prominfo['type'] == 0){
				$goods['price'] = $goods['shop_price']*$prominfo['expression']/100;//打折优惠
			}elseif($prominfo['type'] == 1){
				$goods['price'] = $goods['shop_price']-$prominfo['expression'];//减价优惠
			}elseif($prominfo['type']==2){
				$goods['price'] = $prominfo['expression'];//固定金额优惠
			}
            $goods['name']=$prominfo['name'];//促销标题
		}else{
            $goods['is_end'] = 5;//活动已结束
        }
	}
	
	if(!empty($prominfo)){
		$goods['start_time'] = $prominfo['start_time'];
		$goods['end_time'] = $prominfo['end_time'];
	}
    if($goods['is_end']==5){
        $prom['prom_type'] = $prom['prom_id'] = 0 ;//活动已过期,恢复成普通商品
        M('goods')->where("goods_id", $goods_id)->save($prom);
    }
	
	
	return $goods;
}

/**
 * 查看订单是否满足条件参加活动
 * @param order_amount 订单应付金额
 */
//function get_order_promotion($order_amount,$total_amount){
//    if(!isset($total_amount)){
//        $total_amount=$order_amount;
//    }
//	$parse_type = array('0'=>'满额打折','1'=>'满额优惠金额','2'=>'满额送倍数积分','3'=>'满额送优惠券','4'=>'满额免运费');
//	$now = time();
//	$prom = M('prom_order')->where("type<2 and end_time>$now and start_time<$now and money<=$total_amount")->order('money desc')->find();
//	$res = array('order_amount'=>$order_amount,'order_prom_id'=>0,'order_prom_amount'=>0);
//	if($prom){
//		if($prom['type'] == 0){
//			$res['order_amount']  = round($order_amount*$prom['expression']/100,2);//满额打折
//			$res['order_prom_amount'] = $order_amount - $res['order_amount'] ;
//			$res['order_prom_id'] = $prom['id'];
//		}elseif($prom['type'] == 1){
//			$res['order_amount'] = $order_amount- $prom['expression'];//满额优惠金额
//			$res['order_prom_amount'] = $prom['expression'];
//			$res['order_prom_id'] = $prom['id'];
//		}
//	}
//	return $res;
//}
function get_order_promotion($order_amount,$num,$suppliers_id){
//    if(!isset($total_amount)){
//        $total_amount=$order_amount;
//    }
    $order_amount = $order_amount*$num;
	$parse_type = array('0'=>'满额打折','1'=>'满额优惠金额','2'=>'满额送倍数积分','3'=>'满额送优惠券','4'=>'满额免运费');
	$now = time();
	$prom = M('prom_order')->where("type<2 and end_time>$now and start_time<$now and money<=$order_amount and suppliers_id=$suppliers_id")->order('money desc')->find();
	$res = array('order_amount'=>$order_amount,'order_prom_id'=>0,'order_prom_amount'=>0);
	if($prom){
		if($prom['type'] == 0){
			$res['order_amount']  = round($order_amount*$prom['expression']/100,2);//满额打折
			$res['order_prom_amount'] = $order_amount - $res['order_amount'] ;
			$res['order_prom_id'] = $prom['id'];
		}elseif($prom['type'] == 1){
			$res['order_amount'] = $order_amount- $prom['expression'];//满额优惠金额
			$res['order_prom_amount'] = $prom['expression'];
			$res['order_prom_id'] = $prom['id'];
		}
	}
	return $res;
}

/**
 * 计算订单金额
 * @param type $user_id  用户id
 * @param type $order_goods  购买的商品
 * @param type $shipping  物流code
 * @param type $shipping_price 物流费用, 如果传递了物流费用 就不在计算物流费
 * @param type $province  省份
 * @param type $city 城市
 * @param type $district 县
 * @param type $pay_points 积分
 * @param type $user_money 余额
 * @param type $coupon_id  优惠券
 * @param type $couponCode  优惠码
 */

function calculate_price($user_id = 0, $order_goods, $shipping_code = '', $shipping_price = 0, $province = 0, $city = 0, $district = 0, $pay_points = 0, $user_money = 0, $coupon_id = 0, $couponCode = '')
{
    $cartLogic = new app\home\logic\CartLogic();
    $user = M('users')->where("user_id", $user_id)->find();// 找出这个用户

    if (empty($order_goods)){
        return array('status' => -9, 'msg' => '商品列表不能为空', 'result' => '');
    }

    $goods_id_arr = get_arr_column($order_goods, 'goods_id');
    $goods_arr = M('goods')->where("goods_id in(" . implode(',', $goods_id_arr) . ")")->cache(true,TPSHOP_CACHE_TIME)->getField('goods_id,weight,market_price,is_free_shipping'); // 商品id 和重量对应的键值对
    foreach ($order_goods as $key => $val) {
        // 如果传递过来的商品列表没有定义会员价
        if (!array_key_exists('member_goods_price', $val)) {
            $user['discount'] = $user['discount'] ? $user['discount'] : 1; // 会员折扣 不能为 0
            $order_goods[$key]['member_goods_price'] = $val['member_goods_price'] = $val['goods_price'] * $user['discount'];
        }
        //如果商品不是包邮的
        if ($goods_arr[$val['goods_id']]['is_free_shipping'] == 0)
            $goods_weight += $goods_arr[$val['goods_id']]['weight'] * $val['goods_num']; //累积商品重量 每种商品的重量 * 数量

        $order_goods[$key]['goods_fee'] = $val['goods_num'] * $val['member_goods_price'];    // 小计
        $order_goods[$key]['store_count'] = getGoodNum($val['goods_id'], $val['spec_key']); // 最多可购买的库存数量
        if ($order_goods[$key]['store_count'] <= 0)
            return array('status' => -10, 'msg' => $order_goods[$key]['goods_name'] . "库存不足,请重新下单", 'result' => '');

        $goods_price += $order_goods[$key]['goods_fee']; // 商品总价
        $cut_fee += $val['goods_num'] * $val['market_price'] - $val['goods_num'] * $val['member_goods_price']; // 共节约
        $anum += $val['goods_num']; // 购买数量
        $order_money[] = get_order_promotion($val['member_goods_price'],$val['goods_num'],$val['suppliers_id']);
    }
    foreach($order_money as $k=>$v){
        $order_prom_id[] = $v['order_prom_id'];
        $order_prom_amount[] = $v['order_prom_amount'];
    }
    $order_prom_id = implode(',',$order_prom_id);
    $order_prom_amount = array_sum($order_prom_amount) ;
    // 优惠券处理操作
    $coupon_price = 0;
    if ($coupon_id && $user_id) {
        $coupon_price = $cartLogic->getCouponMoney($user_id, $coupon_id, 1); // 下拉框方式选择优惠券
    }
    if ($couponCode && $user_id) {
        $coupon_result = $cartLogic->getCouponMoneyByCode($couponCode, $goods_price); // 根据 优惠券 号码获取的优惠券
        if ($coupon_result['status'] < 0)
            return $coupon_result;
        $coupon_price = $coupon_result['result'];
    }
    // 处理物流
    if ($shipping_price == 0) {
        $freight_free = tpCache('shopping.freight_free'); // 全场满多少免运费
        if ($freight_free > 0 && $goods_price >= $freight_free) {
            $shipping_price = 0;
        } else {
            $shipping_price = $cartLogic->cart_freight2($shipping_code, $province, $city, $district, $goods_weight);
        }
    }
    
    $use_percent_point = tpCache('shopping.point_use_percent');     //最大使用限制: 最大使用积分比例, 例如: 为50时, 未50% , 那么积分支付抵扣金额不能超过应付金额的50%
    if($pay_points > 0 && $use_percent_point == 0){
        return array('status' => -1, 'msg' => "该笔订单不能使用积分", 'result' => '积分'); // 返回结果状态
    }
    
    if ($pay_points && ($pay_points > $user['pay_points']))
        return array('status' => -5, 'msg' => "你的账户可用积分为:" . $user['pay_points'], 'result' => ''); // 返回结果状态
    if ($user_money && ($user_money > $user['user_money']))
        return array('status' => -6, 'msg' => "你的账户可用余额为:" . $user['user_money'], 'result' => ''); // 返回结果状态

    $order_amount = bcsub(bcadd($goods_price,$shipping_price,2), $coupon_price,2); // 应付金额 = 商品价格 + 物流费 - 优惠券
    $user_money = ($user_money > $order_amount) ? $order_amount : $user_money;  // 余额支付原理等同于积分
    $order_amount = bcsub($order_amount,$user_money,2) ; //  余额支付抵应付金额
    
    /*判断能否使用积分
     1..积分低于point_min_limit时,不可使用
     2.在不使用积分的情况下, 计算商品应付金额
     3.原则上, 积分支付不能超过商品应付金额的50%, 该值可在平台设置
     @{ */
    $point_rate = tpCache('shopping.point_rate'); //兑换比例: 如果拥有的积分小于该值, 不可使用
    $min_use_limit_point = tpCache('shopping.point_min_limit'); //最低使用额度: 如果拥有的积分小于该值, 不可使用
    
    
    if ($min_use_limit_point > 0 && $pay_points > 0 && $pay_points < $min_use_limit_point) {
        return array('status' => -1, 'msg' => "您使用的积分必须大于{$min_use_limit_point}才可以使用", 'result' => ''); // 返回结果状态
    }
    // 计算该笔订单最多使用多少积分
    //$limit = $order_amount * ($use_percent_point / 100) * $point_rate;
    //if(($use_percent_point !=100 ) && $pay_points > $limit) {
    //   return array('status'=>-1,'msg'=>"该笔订单, 您使用的积分不能大于{$limit}",'result'=>'积分'); // 返回结果状态
    //}
    // }
    $multiple = get_user_point_level($user_id);
    $pay_points = ($pay_points / tpCache('shopping.point_rate'))*$multiple; // 积分支付 100 积分等于 1块钱
    $pay_points = ($pay_points > $order_amount) ? $order_amount : $pay_points; // 假设应付 1块钱 而用户输入了 200 积分 2块钱, 那么就让 $pay_points = 1块钱 等同于强制让用户输入1块钱
    $order_amount = $order_amount - $pay_points; //  积分抵消应付金额

    $order_amount = $order_amount - $order_prom_amount;
    $total_amount = $goods_price + $shipping_price;
    //订单总价  应付金额  物流费  商品总价 节约金额 共多少件商品 积分  余额  优惠券
    $result = array(
        'total_amount' => $total_amount, // 商品总价
        'order_amount' => $order_amount, // 应付金额
        'shipping_price' => $shipping_price, // 物流费
        'goods_price' => $goods_price, // 商品总价
        'cut_fee' => $cut_fee, // 共节约多少钱
        'anum' => $anum, // 商品总共数量
        'integral_money' => $pay_points,  // 积分抵消金额
        'user_money' => $user_money, // 使用余额
        'coupon_price' => $coupon_price,// 优惠券抵消金额
        'order_goods' => $order_goods, // 商品列表 多加几个字段原样返回
        'order_prom_id'=>$order_prom_id,
        'order_prom_amount'=>$order_prom_amount,
    );
    return array('status' => 1, 'msg' => "计算价钱成功", 'result' => $result); // 返回结果状态
}

/*
 * 获取积分倍数
 */
function get_user_point_level($id){
    $user = M('users')->where('user_id',$id)->find();
    $level = M('user_level')->where('level_id = '.$user['level'])->find();
    return $level['multiple'];
}

/**
 * 获取商品一二三级分类
 * @return type
 */
function get_goods_category_tree(){
	$arr = $result = array();
	$cat_list = M('goods_category')->where("is_show = 1")->order('sort_order')->cache(true)->select();//所有分类
	
	foreach ($cat_list as $val){
		if($val['level'] == 2){
			$arr[$val['parent_id']][] = $val;
		}
		if($val['level'] == 3){
			$crr[$val['parent_id']][] = $val;
		}
		if($val['level'] == 1){
			$tree[] = $val;
		}
	}

	foreach ($arr as $k=>$v){
		foreach ($v as $kk=>$vv){
			$arr[$k][$kk]['sub_menu'] = empty($crr[$vv['id']]) ? array() : $crr[$vv['id']];
		}
	}
	
	foreach ($tree as $val){
		$val['tmenu'] = empty($arr[$val['id']]) ? array() : $arr[$val['id']];
		$result[$val['id']] = $val;
	}
	return $result;
}

/**
 * 获取供应商商品一二级分类
 * @return type
 */
function get_shop_category_tree(){
    $arr = $result = array();
    $cat_list = M('goods_category_admin')->where("is_show = 1")->order('sort_order')->cache(true)->select();//所有分类
    
    foreach ($cat_list as $val){
        if($val['level'] == 2){
            $arr[$val['parent_id']][] = $val;
        }
        if($val['level'] == 1){
            $tree[] = $val;
        }
    }

    /*foreach ($arr as $k=>$v){
        foreach ($v as $kk=>$vv){
            $arr[$k][$kk]['sub_menu'] = empty($crr[$vv['id']]) ? array() : $crr[$vv['id']];
        }
    }*/
    
    foreach ($tree as $val){
        $val['tmenu'] = empty($arr[$val['id']]) ? array() : $arr[$val['id']];
        $result[$val['id']] = $val;
    }
    return $result;
}

/**
 * 写入静态页面缓存
 */
function write_html_cache($html){
    $html_cache_arr = C('HTML_CACHE_ARR');
    $request = think\Request::instance();
    $m_c_a_str = $request->module().'_'.$request->controller().'_'.$request->action(); // 模块_控制器_方法
    $m_c_a_str = strtolower($m_c_a_str);
    //exit('write_html_cache写入缓存<br/>');
    foreach($html_cache_arr as $key=>$val)
    {
        $val['mca'] = strtolower($val['mca']);
        if($val['mca'] != $m_c_a_str) //不是当前 模块 控制器 方法 直接跳过
            continue;
        
        if(!is_dir(RUNTIME_PATH.'html'))
                mkdir(RUNTIME_PATH.'html');
        $filename =  RUNTIME_PATH.'html'.DIRECTORY_SEPARATOR.$m_c_a_str;
        // 组合参数  
        if(isset($val['p']))
        {                    
            foreach($val['p'] as $k=>$v)        
                $filename.='_'.$_GET[$v];
        } 
        $filename.= '.html';        
        file_put_contents($filename, $html);
    }    
}

/**
 * 读取静态页面缓存
 */
function read_html_cache(){    
    $html_cache_arr = C('HTML_CACHE_ARR');
    $request = think\Request::instance();
    $m_c_a_str = $request->module().'_'.$request->controller().'_'.$request->action(); // 模块_控制器_方法
    $m_c_a_str = strtolower($m_c_a_str);
    //exit('read_html_cache读取缓存<br/>');
    foreach($html_cache_arr as $key=>$val)
    {
        $val['mca'] = strtolower($val['mca']);
        if($val['mca'] != $m_c_a_str) //不是当前 模块 控制器 方法 直接跳过
            continue;
          
        $filename =  RUNTIME_PATH.'html'.DIRECTORY_SEPARATOR.$m_c_a_str;
        // 组合参数        
        if(isset($val['p']))
        {                    
            foreach($val['p'] as $k=>$v)        
                $filename.='_'.$_GET[$v];
        } 
        $filename.= '.html';
        if(file_exists($filename))
        {
            echo file_get_contents($filename);           
            exit();           
        }
    }    
}

//判断字符串是否经过编码方法
function is_base64($str){
    if($str==base64_encode(base64_decode($str))){
        return true;
    }else{
        return false;
    }
}
//判断字符串是否经过编码方法
function shownickname($str){
    if(is_base64($str)){
        $str=base64_decode($str);
    }
    return $str;
}
/**
 * 获取前台用户信息
 */
function get_user_id(){
    $session_user=session('user');
    if(!empty($session_user)){
        return $session_user;
    }else{
        echo'<script>location.href="/Mobile/User/"</script>';
        //header('Location: http://dltest.dliansoft.com/index.php/Mobile/User/login.html');
        return false;
    }
}

//判断是否已经注册为会员
 function is_reg($fkey){
            $users=M('users');
            $res=$users->field('mobile,subscribe')->where(array('user_id'=>$fkey))->find();

           if($res['subscribe']==0){
                return 'no_subsribe';
                exit;
            }elseif(empty($res['mobile'])){
                return 'no_reg';
                exit;
            }else{
                return 'have_reg';
                exit;
            }
        }


/*
 * $user_id：待发对象用户的id
 * $wx_content为发送模板
 */

function push_wxmessage($user_id,$wx_content,$type='text'){
        $user = M('users')->where("user_id", $user_id)->find();
        $typearry=array('order','reg','order_action');
        if(in_array($type,$typearry)){
            $openid=session('user.openid');
            $appid=session('user.appid');
        }else{
            $openid=$user['openid'];
            $appid=$user['appid'];
        }
        if($user['oauth']== 'weixin')
        {
            $wx_user = M('wx_user')->where(array('appid'=>$appid))->find();
            $jssdk = new \app\mobile\logic\Jssdk($wx_user['appid'],$wx_user['appsecret']);
            $jssdk->push_msg($openid,$wx_content,$type);
        }
}
/*
 * $user_id：待发对象用户的id
 * $wx_content为发送模板
 */

function push_wxtplmessage($user_id,$tplarr,$href,$type){
    $user = M('users')->where("user_id", $user_id)->find();
    $typearry=array('order','reg','order_action');
    if(in_array($type,$typearry)){
        $openid=session('user.openid');
        $appid=session('user.appid');
    }else{
        $openid=$user['openid'];
        $appid=$user['appid'];
    }

    if($user['oauth']== 'weixin')
    {
        $wx_user = M('wx_user')->where(array('appid'=>$appid))->find();
        $jssdk = new \app\mobile\logic\Jssdk($wx_user['appid'],$wx_user['appsecret']);
        $href=add_querystring_var($href,'dltoken',$appid);
        $jssdk->push_tplmsg($openid,$tplarr,$href,$type);
    }
    
}
function push_wxtplmessage_admin($users,$content,$href){
        $time=time();
        $day=floor (($time-$users['last_login'])/3600/24);
        $wx_tplarr=array (
            'first' => 
            array (
              'value' => '尊敬的会员：'.shownickname($users["nickname"]).'您好',
              'color' => '#333',
            ),
            'keyword1' => 
            array (
              'value' => shownickname($users['user_id']),
              'color' => '#333',
            ),
            'keyword2' => 
            array (
              'value' => date('Y-m-d H:i:s'),
              'color' => '#333',
            ),
            'remark' => 
            array (
              'value' => $content,
              'color' => '#333',
            )
         );
       if($users['oauth']== 'weixin')
       {
           $wx_user = M('wx_user')->where(array('appid'=>$users['appid']))->find();
           $jssdk = new \app\mobile\logic\Jssdk($wx_user['appid'],$wx_user['appsecret']);
           $href=add_querystring_var($href,'dltoken',$users['appid']);
           $result=$jssdk->push_tplmsg($users['openid'],$wx_tplarr,$href,'admin');
           return $result;
       }
}

function zhekshow($num){
    return $num/10;
}


//---------------以下为加密函数-----------------
//将数组拼接成url字符串并加密
function encrypt_param($arr){
    $url = "";
    foreach ($arr as $key => $value) {
         $url .= $key . "=" .$value ."&";
    }
    $url = encrypt_url(trim($url,"&"));
    return $url;
}

function keyED($txt,$encrypt_key){       
    $encrypt_key = md5($encrypt_key);
    $ctr=0;       
    $tmp = "";       
    for($i=0;$i<strlen($txt);$i++)       
    {           
        if ($ctr==strlen($encrypt_key))
        $ctr=0;           
        $tmp.= substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1);
        $ctr++;       
    }       
    return $tmp;   
}

function encrypt_link($txt){
    $key=C('MD5_KEY');
    $encrypt_key = md5(mt_rand(0,100));
    $ctr=0;
    $tmp = "";
     for ($i=0;$i<strlen($txt);$i++)
     {
        if ($ctr==strlen($encrypt_key))
            $ctr=0;
        $tmp.=substr($encrypt_key,$ctr,1) . (substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1));
        $ctr++;
     }
     return keyED($tmp,$key);
}
    
function decrypt($txt){ 
    $key=C('MD5_KEY');    
    $txt = keyED($txt,$key);       
    $tmp = "";       
    for($i=0;$i<strlen($txt);$i++)       
    {           
        $md5 = substr($txt,$i,1);
        $i++;           
        $tmp.= (substr($txt,$i,1) ^ $md5);       
    }       
    return $tmp;
}

function encrypt_url($url){
    return rawurlencode(base64_encode(encrypt_link($url)));
}

function decrypt_url($url){
    return decrypt(base64_decode(rawurldecode($url)));
}

function geturl($str){
    $str = decrypt_url($str);
    $url_array = explode('&',$str);
    if (is_array($url_array))
    {
        foreach ($url_array as $var)
        {
            $var_array = explode("=",$var);
            $vars[$var_array[0]]=$var_array[1];
        }
    }
    return $vars;
}
 
//---------------以上为加密函数-结束-----------------


function getJssdk(){
//    $jssdk = new \app\mobile\logic\Jssdk(C('DL_APPID'), C('DL_AppSecret'));
    $signPackage = $_SESSION['signPackage'];
    return $signPackage;
}

//为url添加参数
function add_querystring_var($url, $key, $value) {
 $url=preg_replace('/(.*)(?|&)'.$key.'=[^&]+?(&)(.*)/i','$1$2$4',$url.'&');
 $url=substr($url,0,-1);
 if(strpos($url,'?') === false){
  return ($url.'?'.$key.'='.$value);
 } else {
  return ($url.'&'.$key.'='.$value);
 }
}

function hidtel($phone){
    $IsWhat = preg_match('/(0[0-9]{2,3}[\-]?[2-9][0-9]{6,7}[\-]?[0-9]?)/i',$phone); //固定电话
    if($IsWhat == 1){
        return preg_replace('/(0[0-9]{2,3}[\-]?[2-9])[0-9]{3,4}([0-9]{3}[\-]?[0-9]?)/i','$1****$2',$phone);
    }else{
        return  preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i','$1****$2',$phone);
    }
}

/*退款操作函数*/
function refund($user_id,$order_id){

    $order=M('order')->where('order_id',$order_id)->find();

    if($order['pay_code']=='balance'){//如果是余额支付，则退还至余额
        
        if($order['user_money']>0){
            if(!accountLog($user_id, $order['user_money'],0, '订单取消退款')){
                return array('return_code'=>'fail','result_code'=>'fail');
            };
        }
        if($order['integral']>0){
            if(!accountLog($user_id, 0,$order['integral'], '订单取消返还积分',0,'order_action')){
                return array('return_code'=>'fail','result_code'=>'fail');
            };
        }
        if($order['coupon_price']>0){//如果用了优惠券,退回优惠券
            //返还优惠券
            M('coupon_list')->where(['order_id'=>$order['order_id'],'use_time'=>array('gt',0)])->save(['order_id'=>0,'use_time'=>0]);
        }
        
        return array('return_code'=>'SUCCESS','result_code'=>'SUCCESS');
        exit;
    }
    if($order['pay_code']=='weixin'){
        if($order['user_money']>0){//如果使用了余额抵扣，返回该部分金额到用户余额
            accountLog($user_id, $order['user_money'],0, '订单取消退款');
        }
        if($order['integral']>0){//如果使用了余额抵扣，返回该部分金额到用户余额
            accountLog($user_id, 0,$order['integral'], '订单取消返还积分',0,'order_action');
        }
        if($order['coupon_price']>0){//如果用了优惠券,退回优惠券
            //返还优惠券
            M('coupon_list')->where(['order_id'=>$order['order_id'],'use_time'=>array('gt',0)])->save(['order_id'=>0,'use_time'=>0]);
        }
        //如果是微信付款，退款至微信
        include_once  PLUGIN_PATH."payment/weixin/refund.class.php";
        $refund= new \refund();
        $res=$refund->do_refund($order['order_sn'],$order['total_amount']*100,$order['order_amount']*100);
        return $res;
    }

}

//充值赠送函数
function recharge_give($order_sn){
    //查询该订单是否已经赠送
    
    $recharge=M('recharge')->where('order_sn',$order_sn)->find();
    $condition['start_time']=array('elt',time());
    $condition['end_time']=array('egt',time());
    $condition['money']=$recharge['account'];
    $give_money=M('recharge_give')->where($condition)->getField('give_money');

    if($give_money){
        $res=accountLog($recharge['user_id'], $give_money,0, '充值赠送金额',0,'recharge_give');
        return $res;
    }
    return true;
}